package pri.zey.custom.tools.http;

import android.content.Context;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Iterator;

import pri.zey.custom.tools.TL;
import pri.zey.custom.tools.Tkit;

/**
 * Created by Administrator on 2016/3/9.
 *
 */
public class ZHttpService<T> extends ZHttpAgency {

    private TL TL;

    public ZHttpService(Context mContext, String mMethod, Object mObject, int mRequestMethod) {
        this(mContext, mMethod, mObject, mRequestMethod, null, null);
    }

    public ZHttpService(Context mContext, String mMethod, Object mObject, int mRequestMethod, RequestSuccess mSuccess) {
        this(mContext, mMethod, mObject, mRequestMethod, mSuccess, null);
    }

    public ZHttpService(Context mContext, String mMethod, Object mObject, int mRequestMethod, RequestSuccess mSuccess, RequestFail mFail) {
        this.mContext = mContext;
        this.mMethod = mMethod;
        this.mObject = mObject;
        this.mRequestMethod = mRequestMethod;
        this.mSuccess = mSuccess;
        this.mFail = mFail;
        TL = new TL(this);
    }

    @Override
    public void setOutBuffer() {
        JSONObject jsonObject = (JSONObject) mObject;
        if(jsonObject != null){
            Iterator mIterator = jsonObject.keys();
            while(mIterator.hasNext()){
                try {
                    String name = mIterator.next().toString();
                    String value = jsonObject.getString(name);
                    mOutBuffer.append(name).append("=")
                            .append(value).append("&");
                } catch (JSONException e) {
                    if(mContext != null)
                        //mContext.sendBroadcast(new Intent().setAction(TL.ACTION_Msg_Toasts).putExtra("msg", "网络异常"));
                    TL.e(mMethod + " Error JSONException==============> \n" + e.toString());
                }
            }
        }
        TL.i("你发送的参数：" + mOutBuffer.toString());
    }

    @Override
    public void setConnectionConfig() {
        try {
            mConnection.setDoInput(true);
            mConnection.setDoOutput(true);
            mConnection.setConnectTimeout(TimeOut);
            mConnection.setRequestProperty("accept", "*/*");
            mConnection.setRequestProperty("connection", "Keep-Alive");
            mConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setConnectionType() {
        try {
            mPrintWriter = new PrintWriter(mConnection.getOutputStream());
            mPrintWriter.write(mOutBuffer.toString());
            mPrintWriter.flush();
        } catch (IOException e) {
            if(mContext != null) {
//                mContext.sendBroadcast(new Intent().setAction(TL.ACTION_Msg_Toasts).putExtra("msg", "网络异常"));
            }
            TL.e(mMethod + " Error IOException==============> \n" + e.toString());
        }
    }

    @Override
    public JSONObject setReaderBuffer() {
        JSONObject jObject = null;
        try {
            getReader(mConnection.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            return jObject;
        }
    }

    @Override
    public T getReader(InputStream inputStream) {

        return null;
    }

    @Override
    public void closeObject() {
        try {
            if(mReaderBuffer != null){
                mReaderBuffer.close();
            }
            if(mPrintWriter != null){
                mPrintWriter.close();
            }
            if(mConnection != null){
                mConnection.disconnect();
            }
        } catch (IOException e) {
            TL.e(mMethod + " Error finally-IOException==============> \n" + e.toString());
        }
    }

    @Override
    public void run() {
        super.run();
        TL.e("************************ execute START ************************");
        try {
            URL url;
            if(Tkit.notBlank(this.PrimaryDomain))
                url = new URL(this.PrimaryDomain + "/" + mMethod);
            else if(Tkit.notBlank(this.DeputyDomain))
                url = new URL(this.DeputyDomain + "/" + mMethod);
            else{
                return ;
            }
            TL.e("************************ url: " + url.toString());
            mConnection = (HttpURLConnection) url.openConnection();
            TL.e("************************ setOutBuffer ************************");
            setOutBuffer();
            TL.e("************************ setConnectionConfig ************************");
            setConnectionConfig();
            TL.e("************************ setReaderBuffer ************************");
            setReaderBuffer();
        }  catch (Exception e) {
            TL.e("Error IOException==============> \n" + e.toString());
            TL.e("mMethod : " + mMethod);
        } finally{
            TL.e("************************ execute END *************************");
            closeObject();
        }
    }


}
